package com.lucifer.cloud.boot.blog.chat.common;

import com.fasterxml.jackson.core.type.TypeReference;
import com.lucifer.cloud.boot.blog.chat.util.JsonUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;


@Data
@NoArgsConstructor
@AllArgsConstructor
public class MessageWrapper {

    private MessageType type;

    private String content;

    public MessageWrapper(Message message) {
        this.type = message.getMessageType();
        this.content = message.getText();
    }

    public Message toMessage() {
        return switch (type) {
            case USER -> new UserMessage(content);
            case ASSISTANT -> new AssistantMessage(content);
            case SYSTEM -> new SystemMessage(content);
            case TOOL -> throw new UnsupportedOperationException();
        };
    }

    public static String toConversationStr(List<MessageWrapper> messages) {
        return JsonUtil.toJsonString(messages);
    }

    public static List<MessageWrapper> fromConversationStr(String conversationStr) {
        if(!StringUtils.hasText(conversationStr)){
            return new ArrayList<>();
        }
        TypeReference<List<MessageWrapper>> typeReference = new TypeReference<>() {
        };
        return JsonUtil.toJsonObject(conversationStr, typeReference);
    }

}
